from django_system.role_recognize import check_permission
from django.views import View
from django.http import JsonResponse
from zhineng.models import UserInfo, Classes, College, Course
from user.models import User, Role
import json
from django.utils.decorators import method_decorator
from hashlib import sha256
from pypinyin import lazy_pinyin
from functools import wraps
from .models import Syllabus
from datetime import datetime
from examination.models import TestQuestions, ExaminationResult
from django.db import connection
from break_the_rule.models import Behavior


class StudentView(View):
    """添加学生信息"""

    @method_decorator(check_permission(['市场']))
    def post(self, request):
        # 获取前段传来的数据，json格式
        data = json.loads(request.body.decode())
        # 校验数据不能为空
        if not data.values():
            return JsonResponse({'msg': "前端数据不能为为空"}, status=400)
        # 3.写入数据库
        try:
            password = ''.join(lazy_pinyin(data['username'])) + '123456'
            new_pwd = sha256(password.encode()).hexdigest()
            user = User.objects.create(username=data['username'], phone=data['phone'], password=new_pwd)
            UserInfo.objects.create(age=data['age'], number=data['number'], address=data['address'],
                                    parents=data['parents'], user=user)
            user.roles.add(Role.objects.get(name='学生'))
            class_ = Classes.objects.get(id=request.GET.get('class'))
            class_.user.add(user)
            return JsonResponse({'code': 200, 'msg': '学生信息添加成功'})
        except Exception as e:
            return JsonResponse({'msg': "学生信息添加失败"}, status=500)


class CheckView(View):
    """查询所有学生信息"""

    @method_decorator(check_permission(['市场']))
    def get(self, request):
        students = UserInfo.objects.filter(is_delete=False).all()
        stu_info_list = []
        for i in students:
            if Role.objects.get(name='学生') in i.user.roles.all():
                stu_info_list.append({'number': i.number, 'age': i.age, 'address': i.address, 'parents': i.parents,
                                      'username': i.user.username, 'phone': i.user.phone, 'id': i.id})

        return JsonResponse({'msg': "ok!!!!!!!!", 'data': stu_info_list}, safe=False)


class DeleteView(View):
    """删除学生信息"""

    @method_decorator(check_permission(['市场']))
    def delete(self, request, id):
        try:
            userinfo = UserInfo.objects.get(id=id)
            user = User.objects.get(users=userinfo)
            user.is_delete = True
            user.save()
            return JsonResponse({'msg': '角色删除成功', 'code': 200}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '删除失败%s' % e}, status=500)


class EditView(View):
    """修改学生信息"""

    @method_decorator(check_permission(['市场']))
    def put(self, request, id):
        data = json.loads(request.body)
        number = data['number']
        age = data['age']
        address = data['address']
        parents = data['parents']
        try:
            UserInfo.objects.filter(id=id).update(number=number, age=age, address=address, parents=parents)
            user = UserInfo.objects.filter(id=id).first().user
            user.username = data['username']
            user.phone = data['phone']
            user.save()
            return JsonResponse({'code': 200, 'msg': '修改成功'})
        except Exception as e:
            return JsonResponse({'code': 400, 'msg': f'{e}'}, status=400)

    # 查询信息


class GetinfoView(View):
    """根据id获取单个学生信息"""

    @method_decorator(check_permission(['市场']))
    def get(self, request, id):
        try:
            userinfo = UserInfo.objects.filter(id=id).first()
            user_data = {
                'id': id,
                'username': userinfo.user.username,
                'phone': userinfo.user.phone,
                'address': userinfo.address,
                'parents': userinfo.parents,
                'age': userinfo.age,
                'number': userinfo.number
            }
            return JsonResponse({'code': 200, 'msg': '获取成功', 'data': user_data}, status=200)
        except User.DoesNotExist:
            return JsonResponse({'code': 401, 'msg': '获取失败用户不存在'}, status=401)


# 班主任
class AddTeacherView(View):
    """添加班主任"""

    def get(self, request):
        dean = User.objects.filter(username=request.user).first()
        classes = College.objects.filter(college_dean=dean).first().colleges.all()
        role = Role.objects.filter(name='班主任').first()
        selectable = []
        for i in classes:
            hase_teacher = False
            for k in i.user.all():
                if role in k.roles.all():
                    hase_teacher = True
            if not hase_teacher:
                selectable.append({'id': i.id, 'name': i.classes_name})
        return JsonResponse({'msg': 'ok!!!!!!!!', 'data': selectable},
                            status=200)

    @method_decorator(check_permission(['院长']))
    def post(self, request):
        data = json.loads(request.body)

        # 校验数据不能为空
        if not data.values():
            return JsonResponse({'msg': "前端数据不能为空"}, status=400)
        # 写入数据库
        try:
            class_ = Classes.objects.get(id=data['class'])
            password = ''.join(lazy_pinyin(data['username'])) + '123456'
            new_pwd = sha256(password.encode()).hexdigest()
            user = User.objects.create(username=data['username'], password=new_pwd, phone=data['phone'])
            UserInfo.objects.create(age=data['age'], number=data['number'], address=data['address'],
                                    parents=data['parents'], user=user)
            user.save()  # 确保 user 对象已保存到数据库
            user.roles.add(Role.objects.get(name='班主任'))
            class_.user.add(user)
            return JsonResponse({'code': 200, 'msg': '班主任信息添加成功'})
        except Exception as e:
            return JsonResponse({'msg': '班主任信息添加成功'}, status=500)


class CheckTeacherView(View):
    """查询所有班主任信息"""

    @method_decorator(check_permission(['院长']))
    def get(self, request):
        dean = User.objects.filter(username=request.user).first()
        classes = College.objects.filter(college_dean=dean).first().colleges.all()
        try:
            teachers_list = []
            teachers = UserInfo.objects.filter(is_delete=False).all()
            for i in teachers:
                if Role.objects.get(name='班主任') in i.user.roles.all() and i.user.classes_user.first() in classes:
                    teachers_list.append(
                        {'number': i.number, 'age': i.age, 'address': i.address, 'parents': i.parents,
                         'username': i.user.username, 'phone': i.user.phone, 'id': i.id})
            return JsonResponse({'msg': 'ok!!!!!!!!', 'data': teachers_list}, status=200)
        except Exception as e:
            return JsonResponse({'msg': '获取失败', 'code': 500}, status=500)


class DeleteTeacherView(View):
    """删除班主任信息"""

    @method_decorator(check_permission(['院长']))
    def delete(self, request, id):
        try:
            teacherinfo = UserInfo.objects.get(id=id)
            teacher = User.objects.get(users=teacherinfo)
            teacher.is_delete = True
            teacher.save()
            return JsonResponse({'msg': '班主任删除成功', 'code': 200}, status=201)
        except Exception as e:
            return JsonResponse({'msg': '删除失败%s' % e}, status=500)


class EditTeacherView(View):
    """修改班主任信息"""

    @method_decorator(check_permission(['院长']))
    def put(self, request, id):
        data = json.loads(request.body)
        number = data['number']
        age = data['age']
        address = data['address']
        parents = data['parents']
        try:
            UserInfo.objects.filter(id=id).update(number=number, age=age, address=address, parents=parents)
            user = UserInfo.objects.filter(id=id).first().user
            user.username = data['username']
            user.phone = data['phone']
            user.save()
            return JsonResponse({'code': 200, 'msg': '修改成功'})
        except Exception as e:
            return JsonResponse({'code': 400, 'msg': f'{e}'}, status=400)


class GetinfoteacherView(View):
    """根据id查询单个班主任的信息"""

    @method_decorator(check_permission(['院长']))
    def get(self, request, id):
        try:
            teacherinfo = UserInfo.objects.filter(id=id).first()
            teacher_data = {
                'id': id,
                'username': teacherinfo.user.username,
                'phone': teacherinfo.user.phone,
                'address': teacherinfo.address,
                'parents': teacherinfo.parents,
                'age': teacherinfo.age,
                'number': teacherinfo.number
            }
            return JsonResponse({'code': 200, 'data': teacher_data}, status=200)
        except Exception as e:
            return JsonResponse({'code': 401, 'msg': '获取失败'}, status=401)


class AddOutlineView(View):
    """添加大纲"""

    @method_decorator(check_permission(['院长']))
    def post(self, request):
        # 获取前端传来的数据，json格式
        data = json.loads(request.body.decode())
        course_name = data['course_name']
        course_info = data['course_info']
        college_name = data['college_name']
        cycle = data['cycle']
        college = College.objects.filter(college_name=college_name).first()
        existing_course = Course.objects.filter(course_name=course_name).first()
        if existing_course:
            return JsonResponse({'msg': "添加失败，已存在同名课程"})
        try:
            course = Course.objects.create(course_name=course_name, course_info=course_info)
            syllabus = Syllabus.objects.create(course=course, college=college, cycle=cycle)

            return JsonResponse({'msg': "添加成功", 'code': 200}, status=200)
        except Exception as e:

            return JsonResponse({'msg': "添加失败，原因是%s" % e}, status=500)

    @method_decorator(check_permission(['院长']))
    def get(self, request):

        # 查询所有大纲
        try:
            all_syllabus = Syllabus.objects.filter(is_delete=False)
            syllabus_list = []
            for syllabus in all_syllabus:
                syllabus_list.append({
                    'id': syllabus.id,
                    'course_name': syllabus.course.course_name,
                    'course_info': syllabus.course.course_info,
                    'college_name': syllabus.college.college_name,
                    'cycle': syllabus.cycle,
                    'is_delete': syllabus.is_delete
                })
            return JsonResponse({'msg': '获取成功', 'data': syllabus_list}, status=200)
        except Exception as e:
            return JsonResponse({'msg': '获取失败', 'code': 500}, status=500)

    def delete(self, request):
        try:
            course = Course.objects.get(id=id)
            syllabus = Syllabus.objects.get(course=course)
            syllabus.is_delete = True
            syllabus.save()
            return JsonResponse({'msg': '大纲删除成功', 'code': 200}, status=200)
        except Exception as e:
            return JsonResponse({'msg': '删除失败%s' % e}, status=500)


class GetSyllabusList(View):
    def get(self, request, id):
        try:
            syllabus = Syllabus.objects.filter(id=id).first()
            syllabus_data = {
                'id': syllabus.id,
                'course_name': syllabus.course.course_name,
                'course_info': syllabus.course.course_info,
                'college_name': syllabus.college.college_name,
                'cycle': syllabus.cycle
            }
            return JsonResponse({'data': syllabus_data, 'code': 200}, status=200)
        except Exception as e:
            return JsonResponse({'code': 401, 'msg': '获取失败'}, status=401)


class Editsyllabus(View):
    def put(self, request, id):
        data = json.loads(request.body.decode('utf-8'))
        cycle = data['cycle']
        try:
            syllabus = Syllabus.objects.filter(id=id).update(cycle=cycle)
            course = Syllabus.objects.filter(id=id).first().course
            course.course_name = data['course_name']
            course.course_info = data['course_info']
            course.save()
            return JsonResponse({'code': 200, 'msg': '修改成功'}, status=200)
        except Exception as e:
            return JsonResponse({'code': 400, 'msg': '修改失败'}, status=400)

    # @method_decorator(check_permission(['院长']))
    def delete(self, request, id):
        try:
            syllabus = Syllabus.objects.get(id=id)
            course = Course.objects.get(id=syllabus.course_id)
            course.is_delete = True
            syllabus.is_delete = True  # 将is_delete设置为True
            course.save()
            syllabus.save()
            return JsonResponse({'msg': '大纲删除成功', 'code': 200}, status=200)
        except Exception as e:
            return JsonResponse({'msg': '删除失败%s' % e}, status=500)


class GetAllQuestions(View):
    def get(self, request):
        classes = request.GET.get('classes', '')
        if not classes:
            return JsonResponse({'error': '缺少班级参数'})

        with connection.cursor() as cursor:
            cursor.execute("""
            SELECT classes, EXTRACT(MONTH FROM exam_date) AS month, AVG(score) AS average_score FROM examination_result GROUP BY classes, EXTRACT(MONTH FROM exam_date) ORDER BY month""",
                           {'class': classes})
            monthly_average_scores = cursor.fetchall()

        return JsonResponse({'monthly_average_scores': list(monthly_average_scores)})


class GetAllBehavior(View):

    def get(self, request):
        class_statistics = []

        # 执行 SQL 查询，获取每个班级的总人数和违纪人数
        with connection.cursor() as cursor:
            cursor.execute("""
                SELECT c.classes_name, COUNT(u.id) AS total_students, COUNT(b.id) AS discipline_count
                FROM classes c
                LEFT JOIN classes_user cu ON c.id = cu.classes_id
                LEFT JOIN user u ON cu.user_id = u.id
                LEFT JOIN behavior b ON u.id = b.break_user_id
                GROUP BY c.classes_name;
            """)
            rows = cursor.fetchall()

            for row in rows:
                class_statistics.append({
                    'class_name': row[0],
                    'total_students': row[1],
                    'discipline_count': row[2]
                })

        return JsonResponse({'class_statistics': class_statistics})
